//导入路由相关函数
import component from 'element-plus/es/components/tree-select/src/tree-select-option.mjs'
import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router'

//定义路由数组
const routes = [
  {
    path: '/',
    name: '登录',
    component: () => import('../views/login/index.vue')
  },
  {
    path: '/home',
    name: '首页',
    meta: {
      requireAuth: true
    },
    component: () => import('../views/index/index.vue'),

    children: [
      {
        path: '',
        meta: {
          title: '系统管理'
        },
        children: [
          {
            path: '/user',
            component: () => import('../views/user/index.vue'),
            meta: {
              title: '用户管理'
            }
          },
          {
            path: '/clazz',
            component: () => import('../views/clazz/index.vue'),
            meta: { title: '班级管理' }
          },
          {
            path: '/notice',
            component: () => import('../views/notice/index.vue'),
            meta: { title: '公告管理' }
          }
        ]
      },
      {
        path: '/reporting',
        component: () => import('../views/reporting/index.vue'),
        meta: { title: '报到管理' }
      }
    ]
  }
]

//创建路由实例并传递 `routes` 配置
const router = createRouter({
  history: createWebHashHistory(),
  routes: routes
})


// 添加全局路由守卫
router.beforeEach((to, from, next) => {
  const requireAuth = to.matched.some(record => record.meta.requireAuth)
  // 检查用户是否登录
  //   const isLogin = localStorage.getItem('user')
  //   console.log(isLogin)
  //   if (requireAuth && !isLogin) {
  //     // 如果未登录，则重定向到登录页面
  //     next('/')
  //   }
  //   document.title = to.meta.title
  //   next()
  // })
  const isLogin = !!localStorage.getItem("user");
  if (requireAuth && !isLogin) {
    //跳转登录页面
    next("/")
  } else {
    next()//放行
  }
})
//导出路由实例
export default router